<?php

	/**
	 * @package Yomm
	 * @author bsuter
	 *
	 */
	Class Yomm_Library_CmsPageParser {
		
		public $page_rewrite = null;
		
		public $db = null;
		
		public function __construct($page_rewrite, $theme, $view)
		{
			$this->theme = $theme;
			
			$this->view = $view;
			
			$this->page_rewrite = $page_rewrite;
			
			$this->db = Yomm_Db_Query::getInstance();
			
		}
		
		public function export()
		{
			return $this->cmsObject();
		}
	
		/**
		 * @param $this->get->page
		 * 
		 */
		Protected Function CmsObject()
		{
			/** SELECT * FROM cms_block LEFT JOIN (cms_language, cms_nav) ON (cms_block.language_id = cms_language.id AND cms_block.nav_id = cms_nav.id) WHERE rewrite_link = '{$this->get->page}' */
			$obj = $this->db->select("cms_block", array(
				"cms_block.title" => "title",
				"cms_block.text" => "text"
			), "LEFT JOIN (cms_language, cms_nav) ON (cms_block.language_id = cms_language.id AND cms_block.nav_id = cms_nav.id) WHERE cms_nav.status = 1 AND cms_nav.del = 0 AND rewrite_link = '{$this->page_rewrite}'", false);
			
			if(count($obj) == "0")
			{
				throw new Yomm_Error("the rewrite name \"{$this->page_rewrite}\" does not exists in {content name=\"{$this->page_rewrite}\"}");
				return null;
			}
			
			return $this->Parser_Object($obj);
		}
		
		Protected Function Parser_Object($obj)
		{
			return Yomm_Library_Convert::arrayToObject(array(
				'title' => $obj->title,
				'text' => $this->RegexText(stripslashes($obj->text))
			));
		}
		
		Private Function RegexText($text)
		{
			
			$text = $this->RegexImage($text);
			$text = $this->RegexFile($text);
			$text = $this->devmod_p($text);
			$text = $this->insert_devmod($text);
			$text = $this->filter_parser($text);
			$text = $this->base_regexer($text);
			$text = $this->bb_code($text);
			if(isset($_GET['highlight']))
			{
				$text = $this->highlight_text($text, $_GET['highlight']);
			}
			$text = $this->parse_br($text);
			
			return $text;
		}
		
		/**
		 * PARSE BR...
		 */
		private function parse_br($text)
		{
			return str_replace("[br]", "<br />", $text);
		}
		
		/**
		 * find and replace bbcode with original html tags.
		 * @param $text [string] current cms object text
		 */
		private function bb_code($text)
		{
			$preg = preg_match_all("/\[([0-9a-zA-Z]+)\](.*?)\[\/([0-9a-zA-Z]+)\]/", $text, $result, PREG_SET_ORDER);
			
			foreach($result as $item)
			{
				$text = str_replace($item[0], "<{$item[1]}>{$item[2]}</{$item[3]}>" , $text);
			}
			
			return $text;
		}
		
		private function base_regexer($text)
		{
			$preg = preg_match_all("/\[([a-zA-Z]+) ([a-zA-Z0-9[:space:]\:\;\/\?\#\&\"\ö\ü\ä\_\-\.\=]+)\]/", $text, $result, PREG_SET_ORDER);
			
			foreach($result as $found_item)
			{
				$later_replace = $found_item[0]; 
				
				$class_method = $found_item[1]; 
				
				$method_args = $found_item[2]; 
				
				$args = array();
				
				$atr = preg_match_all("/([a-zA-Z]+)\=\"([a-zA-Z0-9[:space:]\;\:\/\?\#\&\ö\ü\ä\_\-\.\=]+)\"/", $method_args, $res, PREG_SET_ORDER);
				
				foreach($res as $key => $value)
				{
					$args[$value[1]] =  html_entity_decode($value[2]);
				}
				
				$_tmp_obj = new Yomm_Library_CmsPageParserFunctions($class_method, $args, $this->view, $this->theme);
				
				$text = str_replace($later_replace, $this->RegexText($_tmp_obj->get_output()), $text);
				
				unset($_tmp_obj);
			}
			
			return $text;
		}
			
		private function highlight_text($text, $get)
		{
			if(!defined('SiteConfig::HighlightWrapper'))
			{
				throw new Yomm_Error("error: SiteConfig::HighlightWrapper not defined!");
			}
			
			$text = str_replace($get, str_replace('{value}', $get, SiteConfig::HighlightWrapper), $text);
			
			return $text;
		}
		
		private function devmod_p($text)
		{
			preg_match_all("/\<p\>\[(.*)\]\<\/p\>/", $text, $result, PREG_SET_ORDER);
			
			foreach($result as $key => $value)
			{
				$text = str_replace($value[0], '[' . $value[1] . ']', $text);
			}
			
			return $text;
		}
		
		private function filter_parser($text)
		{
			$text = str_replace(array(
				"&auml;", "&ouml;", "&uuml;", "&Auml;", "&Ouml;", "&Uuml;", "&quot;"
			), array(
				"ä", "ö", "ü", "Ä", "Ö", "Ü", "\""
			), $text);
			
			preg_match_all("/\[([a-zA-Z0-9[:space:]\-\.\,\@\ö\ä\ü\Ö\Ä\Ü\:\.\/\?\=\_]+)\|([a-z\_]+)\=\"([a-zA-Z0-9\/\:\&\;\=\.\%\#\@\_\)\(\-\?]+)\"\]/", $text, $result, PREG_SET_ORDER);
		
			if(count($result) > 0)
			{
				foreach($result as $item)
				{
					/*
					 * $item :
					 * 0 = full_found (to replace later!)
					 * 1 = text_to
					 * 2 = filter
					 * 3 = filter_atribute
					 */
					
					$_class_filters = new Yomm_Library_CmsPageParserFilters();
					
					if(method_exists($_class_filters, $item[2]))
					{
						// call new class
						$text = str_replace($item[0], call_user_func_array(array($_class_filters, $item[2]), array($item[1], $item[3])), $text);
					} else {
						$text = str_replace($item[0], "[Filter \"" . $item[2] . "\" exisitiert nicht! f&uuml;r ". $item[0] . "]", $text);
					}
				}	
			}
			
			$text = str_replace(array(
				"ä", "ö", "ü"
			), array(
				"&auml;", "&ouml;", "&uuml;"
			), $text);
			
			return $text;
		}
		
		Private Function RegexFile($text)
		{
			preg_match_all("/\[(Datei|datei|File|file) ([0-9]+)(.*?)\]/", $text, $result, PREG_SET_ORDER);
			
			foreach($result as $item)
			{
				$file = new Yomm_Library_FileHandler();
				
				if(isset($item[3]) && !empty($item[3]))
				{
					preg_match("/\|\"(.*)\"/", $item[3], $txt);
					
					$link = '<a href="' . $file->getFile($item[2]) . '" target="_blank">'.$txt[1].'</a>';	
				} else {
					$link = '<a href="' . $file->getFile($item[2]) . '" target="_blank"><img src="'. SiteConfig::Domain . $file->getFileIcon($item[2]) .'" alt="'.$file->getName($item[2]).'" title="'.$file->getName($item[2]).'" /></a>';
				}
					
				$text = str_replace($item[0], $link, $text);
				
				unset($file);
			}
			
			return $text;
		}
		
		Private Function RegexImage($text)
		{
			preg_match_all("/\[(Foto|foto|Photo|photo|Bild|bild) ([0-9]+)\]/", $text, $result, PREG_SET_ORDER);
		
			foreach($result as $item)
			{
				$image = $this->db->select("cms_image", array("name", "mime", "layout", "text"), "LEFT JOIN (image_lib) ON (image_lib.id = cms_image.image_id) WHERE cms_image.image_id='{$item[2]}'", false);
			
				if($image === false)
				{
					$text = str_replace($item[0], "[error: \"photo {$item[2]}\" does not exists]", $text); continue;
				}
				
				
				switch($image->layout)
				{
					default : // float links
						$text = str_replace($item[0], $this->ParseImageConfig(SiteConfig::ContentImageLeft, SiteConfig::Domain . Yomm_Config::DIR_IMAGES_PATH . $image->name . '_', '.' . $image->mime, $image->text), $text);
					break;
					
					case 2 : // middle with p
						$text = str_replace($item[0], $this->ParseImageConfig(SiteConfig::ContentImageMiddle, SiteConfig::Domain . Yomm_Config::DIR_IMAGES_PATH . $image->name . '_', '.' . $image->mime, $image->text), $text);
					break;
					
					case 3 : // float rechts
						$text = str_replace($item[0], $this->ParseImageConfig(SiteConfig::ContentImageRight, SiteConfig::Domain . Yomm_Config::DIR_IMAGES_PATH . $image->name . '_', '.' . $image->mime, $image->text), $text);
					break;
				}
			}
			
			return $text;
		}
		
		/**
		 * TODO: not yet implemented: $this->view->assign('fields', $this->i18nDevMod($grid->config[$type_choose]['fields']));
		 */
		private function insert_devmod($text)
		{
			$preg = preg_match_all("/\[devmod ([a-zA-Z0-9[:space:]\"\ö\ü\ä\_\-\.\=]+)\]/", $text, $result, PREG_SET_ORDER);
			
			foreach($result as $found_item)
			{	
				$later_replace = $found_item[0]; $match = $found_item[1]; $args = array();
			
				$atr = preg_match_all("/([a-zA-Z]+)\=\"([a-zA-Z0-9\.\_\-]+)\"/", $match, $res, PREG_SET_ORDER);
			
				foreach($res as $found)
				{	
					$args[$found[1]] = $found[2];
				}
				
				if(!isset($args['id'])) { 
					$text = "[devmod tag 'id' missing]"; continue;	
				}
				if(!isset($args['type'])) {
					$text = "[devmod tag 'type' missing]"; continue;	
				}
				
				// collect all inofmrations for this devmod
				$item = $this->db->select("dev_mods", array(
					"dev_sql.name" => "sql_name", 
					"dev_mods.theme" => "mod_theme", 
					"dev_mods.code" => "code",
					"dev_mods.tpl_frontend_list" => "frontend_list",
					"dev_mods.tpl_frontend_add" => "frontend_add"
				), "LEFT JOIN(dev_sql) ON (dev_sql.id = dev_mods.dev_sql_id) WHERE dev_mods.id='{$args['id']}'", false);
				
				// TODO: verify if there IS AN DEVMOD EXISTING!! (count() > 0)
				if($item->mod_theme == '$this->theme') $item->mod_theme = $this->theme;
				
				if($args['type'] == "list") $args['type'] = "frontend_list";
				if($args['type'] == "add") $args['type'] = "frontend_add";
				
				$mod = new Yomm_Devmod_Devmod($item->sql_name, $item->mod_theme);
				
				eval(stripslashes($item->code));
				
				$mod_config = $mod->get_config_by_type($args['type']);
				
				if(count($mod_config) == 0) {
					$text = str_replace($later_replace, '[no \''.$args['type'].'\' config defined]', $text); continue;
				}
				
				$this->view->assign(array(
					'this_config' => $mod_config,
					'grid_check_sum' => $mod->generate_checksum(),
					'devmod' => $mod->type($args['type'])->export(),
					'table_struct' => $mod->analyze_table($item->sql_name)
				));
				
				$this->view->assign($mod->get_env_vars());
				
				if(isset($args['tpl']))
				{
					$_tpl = $args['tpl'];
				} else {
					if(!empty($item->{$args['type']}))
					{
						$_tpl = $item->{$args['type']};
					} else {
						$_tpl = 'share/tpl/grid_'.$args['type'].'.tpl';
					}
				}
				
				$text = str_replace($later_replace, $this->RegexText($this->view->fetch($_tpl)), $text);
			}
			
			return $text;
		}
		
		Private Function ParseImageConfig($config, $name, $mime, $title = "")
		{
			// TODO: $title missing
			return str_replace(array('{name}', '{mime}', '{title}'), array($name, $mime, $title), $config);	
		}
		
		private function i18nDevMod($fields)
		{
			$return = array();
			
			foreach($fields as $key => $value)
			{
				if(is_array($value))
				{
					$return[$key] = $value[$this->i18n->i18n];
				} else {
					$return[$key] = $value;
				}
			}	
			return $return;
		}
		
	}